package org.evil.deus.rss.ui;

import org.evil.deus.rss.R;
import org.evil.deus.rss.provider.RSS;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Window;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.SimpleCursorTreeAdapter;

public class Reader extends Activity {
    
	private ExpandableListView listView = null;
	private Cursor cursor = null;
	private ExpandableListAdapter adapter = null;
	
	private Handler handler = new Handler();
	
	private class Initiator implements Runnable {
		public void run() {
			listView = (ExpandableListView) findViewById(R.id.mainList);
			cursor = getContentResolver().query(RSS.Item.CONTENT_URI, null, null, null, null);
			startManagingCursor(cursor);
			handler.post(new Runnable() {
				public void run() {
					adapter = new SimpleCursorTreeAdapter(Reader.this, 
							 							  cursor,
							 							  R.layout.item,
							 							  R.layout.item, 
							 							  new String [] {RSS.Item.TITLE}, 
							 							  new int [] {R.id.title}, 
							 							  R.layout.expand, 
							 							  new String [] {RSS.Item.DESCRIPTION}, 
							 							  new int [] {R.id.desc}) {
															
															@Override
															protected Cursor getChildrenCursor(Cursor groupCursor) {															
																int _id = groupCursor.getInt(0);
																return managedQuery(RSS.Item.CONTENT_URI, null, RSS.Item._ID + " = ?", new String [] {String.valueOf(_id)}, null);
															}
														};
					listView.setAdapter(adapter);
				}
			});
		}
	}
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_CUSTOM_TITLE);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
        setContentView(R.layout.main);
        Thread init = new Thread(new Initiator());
        init.start();
    }
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
			case R.id.update:
				Intent intent = new Intent(getString(R.string.action_sync));
		        startService(intent);
				return true;
			default:
				return super.onOptionsItemSelected(item);
		}	
	}
}